package org.example.interpreter;

import java.util.HashMap;
import java.util.Stack;

/**
 * @author wangbin
 * @date 2024/4/20
 * @vesion 1.0
 */
public class Calculator {
    private Expression exception;

    public Calculator(String expStr) {
        Stack<Expression> stack = new Stack();

        char[] charArray = expStr.toCharArray();

        Expression left = null;
        Expression right = null;

        for (int i=0;i<charArray.length;i++) {
            char c = charArray[i];
            switch (c) {
                case '+':
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(++i));
                    stack.push(new AddExpression(left,right));
                    break;
                case '-':
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(++i));
                    stack.push(new SubExpression(left,right));
                    break;
                default:
                    stack.push(new VarExpression(String.valueOf(c)));
                    break;
            }

        }
        this.exception =stack.pop();
    }

    public int run(HashMap<String,Integer> var){
        return this.exception.interpreter(var);
    }
}
